package com.ailiwu.www.ailiwu.Fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.activity.CommodityActivity;
import com.ailiwu.www.ailiwu.adapter.HotRecyclerViewAdapter;
import com.ailiwu.www.ailiwu.base.BaseFragment;
import com.ailiwu.www.ailiwu.base.MyApplication;
import com.ailiwu.www.ailiwu.bean.ClassifyGiftSecond;
import com.ailiwu.www.ailiwu.bean.HotCommodityData;
import com.ailiwu.www.ailiwu.url.Urls;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;

/**
 * Author:    XiYoung
 * Version    V1.0
 * Date:      2015/12/2 000216:31
 * Description: 热点界面的数据展示
 * Modification  History:
 * Date         	Author        		Version        	Description
 * -----------------------------------------------------------------------------------
 * 2015/12/2 0002       XiYoung              1.0                   1.0
 * Why & What is modified:
 */
public class HotFragment extends BaseFragment {
    private RecyclerView recyclerView_hot;
    private String next_url;//上拉加载的url
    private HotRecyclerViewAdapter mAdapter;
    private ArrayList<HotCommodityData.DatasEntity.ItemsEntity.DataEntity> listData;
    private ArrayList<ClassifyGiftSecond.DataEntity.ItemsEntity> Datas;
    private static String URL;
    private SwipeRefreshLayout swipeRefreshLayout;
    private HttpUtils get;//xUtils的网络加载模块
    private boolean isLoadingMore = false;
    private GridLayoutManager gridLayoutManager;


    public static HotFragment newInstance(String arg) {
        Bundle args = new Bundle();
        HotFragment fragment = new HotFragment();
        Bundle bundle = new Bundle();
        bundle.putString("urlID", arg);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arg = getArguments();
        if (arg != null) {
            URL = arg.getString("urlID", "");
        }


    }

    @Override
    protected View inflateView() {
        return View.inflate(getActivity(), R.layout.fragment_hot, null);
    }

    @Override
    protected void initView(View view) {
        // 创建xUtils的网络加载模块
        newHttpUtils();

        //获取SwipeRefreshLayout控件
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //设置圈内的颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.mainColor);
        //获取RecyclerView
        recyclerView_hot = (RecyclerView) view.findViewById(R.id.recyclerView_hot);
        //设置网格显示,列数为2
        gridLayoutManager = new GridLayoutManager(MyApplication.mContext, 2);
        recyclerView_hot.setLayoutManager(gridLayoutManager);


    }

    /**
     * 创建xUtils的网络模块加载数据
     */
    private void newHttpUtils() {
        get = new HttpUtils();
        get.configTimeout(100000);//设置连接超时时间
        get.configDefaultHttpCacheExpiry(24 * 3600 * 1000);//设置缓存区中数据的存储时间，单位为毫秒,这里设置为1天.
        get.configHttpCacheSize(4 * 1024 * 1024);//设置缓存区的大小，单位是b字节
    }

    // 加载RecyclerView数据
    @Override
    protected void initData() {
        // 新建适配器使用的数据集合
        listData = new ArrayList();
        Datas = new ArrayList<>();


        //加载分类页面礼物页每个分类Item的数据
        if (!TextUtils.isEmpty(URL)) {
            get.send(HttpRequest.HttpMethod.GET, URL, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {

                    String Json = responseInfo.result;
                    // 开始解析Josn字符串
                    ClassifyGiftSecond secondData = gson.fromJson(Json, ClassifyGiftSecond.class);

                    next_url = secondData.getData().getPaging().getNext_url();//得到上拉加载的url

                    ArrayList<ClassifyGiftSecond.DataEntity.ItemsEntity> items =
                            (ArrayList) secondData.getData().getItems();

                    Datas.addAll(items);


                    // 创建RecyclerView适配器,并进行设置
                    mAdapter = new HotRecyclerViewAdapter(MyApplication.mContext, Datas);
                    mAdapter.setItemClickListener(new HotRecyclerViewAdapter.ItemClickListener() {
                        @Override
                        public void onItemClick(View view, int postion) {
                            int id = Datas.get(postion).getId();
                            String url_commodity = Urls.URL_COMMODITY + "/" + id;
                            Intent intent = new Intent(MyApplication.mContext, CommodityActivity.class);
                            intent.putExtra("url_commodity", url_commodity);
                            intent.putExtra("COMMODITYID", id);
                            startActivity(intent);
                        }
                    });
                    LoadMoreListener();
                    recyclerView_hot.setAdapter(mAdapter);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Log.i("oye", "failure:  " + e.getMessage() + "  " + s);
                }
            });

        } else {//加载热门页面数据
            get.send(HttpRequest.HttpMethod.GET, Urls.URL_HOT, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {

                    String Json = responseInfo.result;
                    // 开始解析Josn字符串
                    HotCommodityData hotCommodityData = gson.fromJson(Json, HotCommodityData.class);

                    next_url = hotCommodityData.data.paging.next_url;//得到上拉加载的url
                    Log.i("oye", "第一次得到的下一页url：：：" + next_url);
                    ArrayList<HotCommodityData.DatasEntity.ItemsEntity> items =
                            (ArrayList) hotCommodityData.data.items;
                    for (int i = 0; i < items.size(); i++) {
                        listData.add(items.get(i).data);
                    }

                    // 创建RecyclerView适配器,并进行设置
                    mAdapter = new HotRecyclerViewAdapter(MyApplication.mContext, listData);
                    mAdapter.setItemClickListener(new HotRecyclerViewAdapter.ItemClickListener() {
                        @Override
                        public void onItemClick(View view, int postion) {
                            int id = listData.get(postion).id;
                            String url_commodity = Urls.URL_COMMODITY + "/" + id;
                            Intent intent = new Intent(MyApplication.mContext, CommodityActivity.class);
                            intent.putExtra("url_commodity", url_commodity);
                            intent.putExtra("COMMODITYID", id);
                            startActivity(intent);
                        }
                    });
                    LoadMoreListener();
                    recyclerView_hot.setAdapter(mAdapter);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Log.i("oye", "failure:  " + e.getMessage() + "  " + s);
                }
            });
        }
        /**
         *  设置下拉刷新监听
         */
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (swipeRefreshLayout.isRefreshing())
                            swipeRefreshLayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });


    }

    /**
     * 设置上拉加载监听的方法
     */
    public void LoadMoreListener() {
        recyclerView_hot.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastitem = gridLayoutManager.findLastVisibleItemPosition();// 得到的是一行的第一个
                Log.i("oye", "lastitem =" + lastitem);
                Log.i("oye", "adapter.getItemCount() =" + mAdapter.getItemCount());
                if (dy > 0 && (lastitem == mAdapter.getItemCount() - 1)) {
                    if (!isLoadingMore) {
                        loadMore();
                    }
                }
            }
        });
    }

    public void loadMore() {
        isLoadingMore = true;
        get.send(HttpRequest.HttpMethod.GET, next_url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String Json = responseInfo.result;
                if (!TextUtils.isEmpty(URL)) {
                    // 开始解析Josn字符串
                    ClassifyGiftSecond secondData = gson.fromJson(Json, ClassifyGiftSecond.class);
                    next_url = secondData.getData().getPaging().getNext_url();//得到上拉加载的url
                    ArrayList<ClassifyGiftSecond.DataEntity.ItemsEntity> items =
                            (ArrayList) secondData.getData().getItems();
                    Datas.addAll(items);
                    mAdapter.notifyDataSetChanged();
                    isLoadingMore = false;
                } else {
                    // 开始解析Josn字符串
                    HotCommodityData hotCommodityData = gson.fromJson(Json, HotCommodityData.class);

                    next_url = hotCommodityData.data.paging.next_url;//得到上拉加载的url
                    Log.i("oye", "第一次之后加载的下一页 ::" + next_url);
                    ArrayList<HotCommodityData.DatasEntity.ItemsEntity> items =
                            (ArrayList) hotCommodityData.data.items;
                    ArrayList<HotCommodityData.DatasEntity.ItemsEntity.DataEntity> temp =
                            new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        temp.add(items.get(i).data);
                    }
                    listData.addAll(temp);
                    mAdapter.notifyDataSetChanged();
                    isLoadingMore = false;
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.i("oye", "failure:  " + e.getMessage() + "  " + s);
            }
        });
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (getView() != null) {
            getView().setVisibility(menuVisible ? View.VISIBLE : View.INVISIBLE);
        }
    }

}
